package task.manager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity class for viewing tasks.
 * 
 * @author Harrison Saylor, Aaron Mead, Marc Huet, Greg Ruskin
 * @version 2
 */
public class TaskViewActivity extends Activity{
	
	private static final int DIALOG_NEW_CATEGORY = 1;
	private static final int DIALOG_CHOOSE_SORT = 2;
	private static final int DATE_DIALOG_ID = 0;

	private UserDataFacade userDataFacade;
	private TaskSorter[] taskSorters = {new TaskSorterAll(),new TaskSorterCompletion(),new TaskSorterDate()};
	private int sortChoice = 0;
	private TaskSorter taskSorter;
	private String activeCategory;
	
	private int mMonth;
	private int mDay;
	private int mYear;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        
        setContentView(R.layout.taskviewactivity);
        
        userDataFacade = UserDataFacade.getInstance();
        taskSorter = taskSorters[userDataFacade.getSortType()];
        final ActionBar bar = getActionBar();
        
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		loadTabs();
		
    }
	
	private void loadTabs() {
		String[] catNames = userDataFacade.getCatNames();
		for(int i=0;i<catNames.length;i++){
			addTab(catNames[i]);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {


		// Adds button to Action Bar
		MenuItem logoutButton = menu.add("Logout");
		MenuItem sortButton = menu.add("Sort");
		//MenuItem newButton = menu.add("New Category");
		MenuItem mapButton = menu.add("Map");

		logoutButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		logoutButton.setIcon(android.R.drawable.ic_menu_revert);
		sortButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		sortButton.setIcon(android.R.drawable.ic_menu_share);
		//newButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		//newButton.setIcon(android.R.drawable.ic_menu_add);
		mapButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		mapButton.setIcon(android.R.drawable.ic_menu_mapmode);


		return true;

	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("Logout")){
			Intent nextScreen = new Intent(getApplicationContext(),
					TaskManager2Activity.class);
			startActivity(nextScreen);
			finish();
		}
		if (item.getTitle() == "Sort") {
			showDialog(DIALOG_CHOOSE_SORT);

		}
		if (item.getTitle() == "Map") {
			Intent nextScreen = new Intent(getApplicationContext(),
					GoogleMapsView.class);
			startActivity(nextScreen);
		}
		
		return true;
	}
	
	public void addTab(String categoryName) {
        final ActionBar bar = getActionBar();
        
        final String text = categoryName;
        int tabCount = bar.getTabCount();
        boolean selected = false;
        if(categoryName.equals("+ New\nCategory")&&(tabCount <=1)){
        	selected = true;
        }
        if(categoryName.equals("All")){
        	selected = true;
        }
        
        bar.addTab(bar.newTab()
                .setText(text)
                .setTabListener(new TabListener(new TabContentFragment())), tabCount, selected);
    }
	
    public void addTab(View v) {
    	final ActionBar bar = getActionBar();
        final int tabCount = bar.getTabCount();
        final String text = "Tab " + tabCount;
        addTab(text);
    }

    public void removeTab(View v) {
        final ActionBar bar = getActionBar();
        bar.removeTabAt(bar.getTabCount() - 1);
    }

    public void removeAllTabs(View v) {
        getActionBar().removeAllTabs();
    }

    /**
     * A TabListener receives event callbacks from the action bar as tabs
     * are deselected, selected, and reselected. A FragmentTransaction
     * is provided to each of these callbacks; if any operations are added
     * to it, it will be committed at the end of the full tab switch operation.
     * This lets tab switches be atomic without the app needing to track
     * the interactions between different tabs.
     *
     * NOTE: This is a very simple implementation that does not retain
     * fragment state of the non-visible tabs across activity instances.
     * Look at the FragmentTabs example for how to do a more complete
     * implementation.
     */
    private class TabListener implements ActionBar.TabListener {
        private TabContentFragment mFragment;

        public TabListener(TabContentFragment fragment) {
            mFragment = fragment;
        }

        @SuppressWarnings("deprecation")
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
        	if (tab.getText().equals("+ New\nCategory")){
        		showDialog(DIALOG_NEW_CATEGORY);
        	}
        	else{
        	activeCategory = (String) tab.getText();
        	userDataFacade.setActiveCategory(activeCategory);
        	//mFragment.loadFragmentContent();
            ft.add(R.id.fragment_content, mFragment);
        	}
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(mFragment);
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(TaskViewActivity.this, "Reselected!", Toast.LENGTH_SHORT).show();
        }

    }

    private class TabContentFragment extends Fragment {
    	
        //String[] list = new String[dummyList.size()];

        String[] list;
        ListView lv;
        View fragView;
        
        public TabContentFragment() {
			super();
			
            //mText = text;
            //dummyList.toArray(list);
            
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            fragView = inflater.inflate(R.layout.action_bar_tab_content, container, false);

            //TextView text = (TextView) fragView.findViewById(R.id.text);
            //text.setText(mText);
            //System.out.println(fragView);
            loadFragmentContent();
            return fragView;
        }
        
        public void loadFragmentContent(){
        	list = taskSorter.getSortedTaskArray(activeCategory);
        	
        	 lv = (ListView) fragView.findViewById(R.id.list);
             lv.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,list));
             lv.setOnItemClickListener(new TaskOnItemClickListener());
        	
        }
        
        private class TaskOnItemClickListener implements OnItemClickListener{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String selectedItem = (String) lv.getItemAtPosition(position);
				System.out.println("Selected Task: " + selectedItem);
				if(selectedItem.equals("Add New Task")){
					Intent nextScreen = new Intent(getApplicationContext(),
							TaskCreationActivity.class);
					startActivity(nextScreen);
					finish();
				}
				else{
					userDataFacade.setActiveTask(selectedItem);
					Intent nextScreen = new Intent(getApplicationContext(),
							TaskActivity.class);
					startActivity(nextScreen);
					finish();
				}
				
			}
        	
        }
    
    }
	
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    
                	mYear = year;
                	mMonth = monthOfYear;
                	mDay = dayOfMonth;
                	
                	
                    userDataFacade.setSortDate(mYear,mMonth,mDay);

                }
            };
    
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mDateSetListener,
	                    mYear, mMonth, mDay);
		case DIALOG_NEW_CATEGORY:
			// This example shows how to add a custom layout to an AlertDialog
			final EditText input = new EditText(this);
			return new AlertDialog.Builder(TaskViewActivity.this)
					.setIconAttribute(android.R.attr.alertDialogIcon)
					.setTitle("New Category")
					.setView(input)
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String catName = input.getText().toString();
									//addTab(catName);

									/*
									 * Add the string to an array stored in the
									 * data facade
									 */
									userDataFacade.addCategory(catName);
									try {
										userDataFacade.saveCatData();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									Intent nextScreen = new Intent(getApplicationContext(), LoadScreen.class);
					        		startActivity(nextScreen);
					        		finish();
								}
							})
					.setNegativeButton(R.string.alert_dialog_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();
		case DIALOG_CHOOSE_SORT:
			
			String[] items = {"All", "By Completion", "By Date"};
			return new AlertDialog.Builder(TaskViewActivity.this)
	        .setIconAttribute(android.R.attr.alertDialogIcon)
	        .setTitle("Select Sort Method")
	        .setSingleChoiceItems(items, userDataFacade.getSortType(), new DialogInterface.OnClickListener() {
	            @SuppressWarnings("deprecation")
				public void onClick(DialogInterface dialog, int whichButton) {
	            	sortChoice = whichButton;
	            	switch (whichButton){
	            	case(2):                
	            		showDialog(DATE_DIALOG_ID);
	            	}

	                /* User clicked on a radio button do some stuff */
	            }
	        })
	        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	userDataFacade.setSortType(sortChoice);
	            	
	            	Intent nextScreen = new Intent(getApplicationContext(), LoadScreen.class);
	        		startActivity(nextScreen);
	        		finish();
	                /* User clicked Yes so do some stuff */
	            }
	        })
	        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {

	                /* User clicked No so do some stuff */
	            }
	        })
	       .create();
		}
		return null;
	}
	
}
